package com.example.demo.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

//这个类 负责被 服务器接收到的文件上传到 oss服务器上。 返回url链接
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class AliOSSUtils {
    /*
    // Endpoint以华东1（杭州）
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

    //密钥 Key Secret
    private String accessKey="LTAI5tMviXaxiVPYHURnY43M";
    private String accessKeySecret="ukqN0gRCAvxnSJ7szmCpxno5mHzo5n";

    // Bucket名称
    private String bucketName = "tlias-imgs";
    */

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKey}")
    private String accessKey;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    public String uploadOSS(MultipartFile image){

        String fileName = image.getOriginalFilename(); //获取上传文件的 文件名字    中国梦.txt  a.txt.java
        UUID uuid = UUID.randomUUID(); // afads-adfa-dfa-sdf-ag-adsf-dsfh-gfhj-fg
        String[] split = fileName.split("\\.");
        String newFileName = uuid+"."+split[split.length-1];
        //保存到 OSS服务器上的 文件名就叫做 newFileName

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey,accessKeySecret);
        try {
            ossClient.putObject(bucketName,newFileName, image.getInputStream() );
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ossClient.shutdown();
        }
        // https://tlias-imgs.oss-cn-hangzhou.aliyuncs.com/abcd1234hahaha.jpg
        // https:// Bucket名称. oss-cn-hangzhou.aliyuncs.com / 文件名字
        String[] split1 = endpoint.split("//"); //https:   oss-cn-hangzhou.aliyuncs.com
        String url = split1[0]+"//"+bucketName+"."+split1[1]+"/"+newFileName;
        return url;
    }

}
